package com.optitronics.util;

import java.util.Collection;
import java.util.regex.Pattern;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class OptitronicsUtils {

	public static boolean isUserAdmin() {
		return checkForUserRole(OptitronicsConstants.ROLE_ADMIN);
	}

	public static boolean isUserReseller() {
		return checkForUserRole(OptitronicsConstants.ROLE_RESELLER);
	}

	public static String getActiveUser() {
		return SecurityContextHolder.getContext().getAuthentication().getName();
	}

	public static boolean checkForUserRole(String roleName) {
		Collection<GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
				.getAuthorities();
		boolean hasRole = false;
		for (GrantedAuthority ga : authorities) {
			if (roleName.equals(ga.getAuthority())) {
				hasRole = true;
			}
		}
		return hasRole;
	}

	public static String getLoggerPrefix() {
		String username = OptitronicsUtils.getActiveUser() != null ? OptitronicsUtils.getActiveUser() : "N/A";
		return "---" + username + "---";
	}

	public static boolean validateEmail(String email) {
		Pattern pattern = Pattern.compile(OptitronicsConstants.EMAIL_PATTERN);
		return pattern.matcher(email).matches();
	}

}
